package com.example.demo.init;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.core.DefineConstant;
import com.example.demo.entity.DictEntity;
import com.example.demo.entity.base.ResponseEntity;
import com.example.demo.entity.base.TreeEntity;
import com.example.demo.system.service.SystemManageService;
import com.example.demo.util.RedisUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class InitRedisData implements InitializingBean{
	
	@Autowired
	private SystemManageService systemManageService;
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public void afterPropertiesSet() {
		// TODO Auto-generated method stub
		log.debug("redis缓存数据加载");
		
		log.debug("加载组织机构树数据");
		ResponseEntity<Map<String, Object>> orgRet = systemManageService.getOrgTree();
		
		if(HttpServletResponse.SC_OK==orgRet.getCode()) {
			List<Map<String, Object>> orgTree = orgRet.getRetlist();
			
			try {
				redisUtil.addString(DefineConstant.ORG_CACHE_KEY, JSONObject.toJSONString(orgTree), null);
			} catch (Exception e) {
				log.error("将组织机构树数据添加到redis失败",e);
			}
		}
		
		log.debug("加载菜单树数据");
		
		ResponseEntity<TreeEntity> menuRet = systemManageService.getMenuTree();
		
		if(HttpServletResponse.SC_OK==menuRet.getCode()) {
			List<TreeEntity> menuTree = menuRet.getRetlist();
			
			try {
				redisUtil.addString(DefineConstant.MENU_CACHE_KEY, JSONObject.toJSONString(menuTree), null);
			} catch (Exception e) {
				log.error("将菜单树数据添加到redis失败",e);
			}
		}
		
		log.debug("加载字典数据");
		
		ResponseEntity<Map<Integer, List<DictEntity>>> dictRet = systemManageService.getDictData();
		
		if(HttpServletResponse.SC_OK==dictRet.getCode()) {
			Map<Integer, List<DictEntity>> dictDatas = dictRet.getRetdata();
			
			Map<String, String> redisHash = systemManageService.installDict2RedisHash(dictDatas);
			
			try {
				redisUtil.remove(DefineConstant.DICT_CACHE_KEY);
				
				redisUtil.addHashValue(DefineConstant.DICT_CACHE_KEY, redisHash, null);
			} catch (Exception e) {
				log.error("将字典表数据加载到redis失败",e);
			}
		}
		
	}

}
